package com.aitemv.web.user;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aitemv.entity.UserEntity;
import com.aitemv.services.UserService;
import com.aitemv.utils.DataUtil;
import com.aitemv.web.base.BaseAction;

/**
 * 
 * @author lyvee
 * 用户注册action
 */
@Controller
public class UserRegsiterAction extends BaseAction {

	@Autowired
	private UserService userService;

	@Override
	@RequestMapping(value = "register.htm", method = RequestMethod.GET)
	public String forward(ModelMap model, HttpServletRequest request,
			HttpServletResponse response) {
		return "register";
	}

	/**用户注册***/
	@RequestMapping(value = "registerdo.htm", method = RequestMethod.POST)
	public String register(@ModelAttribute
	UserEntity user, HttpServletRequest request, HttpServletResponse response) {
		user.setCtime(DataUtil.getDate(new Date()));
		user.setFlag("1");//删除标识
		user.setRole(1);//设置用户权限
		userService.addUser(user);//保存用户
		HttpSession session = request.getSession(false);//获得session
		if(null== session)//如果session为空
			session = request.getSession(true);	
		session.setAttribute("userAcc", user.getAccount());
		return "redirect:/userCenter.htm";//跳转到一个action
	}

	/***ajax用于检测用户是否存在***/
	@RequestMapping(value = "/checkAcc.do", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> checkAcc(@RequestParam String account) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if(!StringUtils.isEmpty(account)){
			if(userService.checkAcc(account)){
				modelMap.put("success", "true");
			}else{
				modelMap.put("success", "false");
			}
		}else{
				modelMap.put("success", "false");
		}
		return modelMap;
	}
	
}
